<script setup lang="ts">
import { Upload } from '@element-plus/icons-vue'
import { watch,ref,inject } from 'vue'
import type { PicLink, PicLinkFunc, UploadResType } from '@/types'

const props = defineProps<{
  picTitle:string,
  picDesc:string,
  value:string,
  index:number
}>()

const updatePicLink = inject<PicLinkFunc>('updatePicLink',(link:PicLink)=>{})

const imageUrl = ref('');
watch(()=>props.value, async (newVal) => {
  if(newVal){
    const response = await fetch(newVal)
    const blob = await response.blob()
    // 使用 Blob 创建 File 对象
    const file = new File([blob], 'filename.jpg', { type: blob.type })
    imageUrl.value = URL.createObjectURL(file)
  }else{
    imageUrl.value = '';
  }
})

const handleAvatarSuccess = (res:UploadResType)=>{
  updatePicLink({
    link: res.imageUrl,
    index: props.index,
  })
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 5
  if (!isJPG) {
    alert('只能上传 JPG/PNG 格式图片!')
    return false
  }
  if (!isLt2M) {
    alert('图片大小不能超过 5MB!')
    return false
  }
  return true
}
</script>

<template>
  <div class="pic-image">
    <el-upload
      class="avatar-uploader"
      action="/api/upload"
      name="image"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="value" :src="value" alt="" class="avatar" />
      <div class="desc-upload" v-else>
        <el-icon><Upload /></el-icon>
        上传图片
      </div>
      <!--      <img v-if="imageUrl" :src="imageUrl" class="avatar" />-->
      <!--      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
    </el-upload>
    <div class="pic-image-bottom">
      <div class="pic-image-title">{{picTitle}}</div>
      <div class="pic-image-desc">{{picDesc}}</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.pic-image{
  width: 200px;
  height: 300px;
  border: 1px solid var(--font-color-lightest);
  border-radius: var(--border-radius-md);
  color: var(--font-color-light);
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar-uploader{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--font-color-lightest);
    width: 100%;
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  .pic-image-bottom{
    height: 100px;
    font-size: var(--font-size-lg);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }
}
</style>
